package gui.scheduler;

import javax.swing.*;
import javax.swing.border.EtchedBorder;

import java.awt.*;

import java.util.*;

import util.UserData;
import util.CalendarInterface;

public class MonthPanel extends JPanel {
	private String days[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday","Saturday"};
	private Cell cells[]= new Cell[5*7];
	public MonthPanel() {
		// delete
		//UserData.setDaysToGenerate(new boolean[] { false,true,false,true,false,true,false });
		// end
		this.setLayout(new BorderLayout());

		JPanel tmp = new JPanel();
		tmp.setLayout(new GridLayout(5,7,0,0));

		for(int i=0; i<5*7; i++) {
			cells[i]=new Cell();
			tmp.add(cells[i]);
		}
		this.add(tmp,BorderLayout.CENTER);

		tmp = new JPanel();
		tmp.setLayout(new GridLayout(1,7,0,0));
		for(String day : days)
			tmp.add(new DayLabel(day));
		this.add(tmp,BorderLayout.NORTH);
	}

	public void setMonth(int year, int month) {
		//month-=1; // Jan = 0
		Calendar cal = new GregorianCalendar(year,month,1);
		Calendar today = new GregorianCalendar();
		while(cal.get(Calendar.DAY_OF_WEEK)!=Calendar.SUNDAY) cal.add(Calendar.DATE, -1);
		Calendar end = (Calendar) cal.clone();
		end.add(Calendar.DAY_OF_MONTH,5*7);
		CalendarInterface.MealEvent mealEvent[] = null;
		try {
			mealEvent = CalendarInterface.getMealsBetween(cal.getTime(),end.getTime());
			//System.out.println(cal.getTime()+" "+end.getTime());
			//System.out.println(Arrays.toString(mealEvent));
		} catch(Exception e) {
			e.printStackTrace();
		}
		Calendar day = new GregorianCalendar();
		for(int i=0; i<5*7; i++) {
			String meal = null;
			boolean usr=false;
			for(int j=0; j<mealEvent.length; j++) {
				day.setTime(mealEvent[j].getDate());
				if( cal.get(Calendar.DAY_OF_YEAR)==day.get(Calendar.DAY_OF_YEAR) &&
						cal.get(Calendar.YEAR)==day.get(Calendar.YEAR) ) {
					meal = mealEvent[j].getMealName();
					usr = mealEvent[j].getSource().equals("USR");
				}
			}
			cells[i].setUserMade(usr);
			cells[i].setFields(cal, cal.get(Calendar.MONTH)!=month, meal);
			if( cal.get(Calendar.DAY_OF_YEAR)==today.get(Calendar.DAY_OF_YEAR) &&
					cal.get(Calendar.YEAR)==today.get(Calendar.YEAR))
				cells[i].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED,
						new Color(200,200,150),new Color(255,255,143)));
			else
				cells[i].setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
			cal.add(Calendar.DAY_OF_MONTH, 1);
		}
	}
}
class DayLabel extends JPanel {
	private JLabel label;
	public DayLabel(String str) {
		label = new JLabel(str,JLabel.CENTER);
		this.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
		this.add(label);
	}
}
